import { loginApi, getUserProfileApi, getUserInfoApi } from '@/api/user'
// 不起别名也没有问题
import { setToken as setTokenFn, getToken, removeToken } from '@/utils/auth'
const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    setTokenFn(newToken)
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  logout(state) {
    state.token = ''
    removeToken()
    state.userInfo = {}
  }
}
const getters = {}
const actions = {
  /**
   * 登录
   * @param {*} store
   * @param {*} data
   * @returns
   */
  login(store, data) {
    return new Promise((resolve, reject) => {
      loginApi(data).then(res => {
        const token = res.data
        store.commit('setToken', token)
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  /**
   * 获取用户信息
   */
  async getUserProfile({ commit }) {
    const res = await getUserProfileApi()
    const res2 = await getUserInfoApi(res.data.userId)
    const baseInfo = {
      ...res.data,
      ...res2.data
    }
    // const { commit } = store
    commit('setUserInfo', baseInfo)
    return baseInfo
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions
}
